﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using WT.OpenIddict.Domain.Roles;
using WT.OpenIddict.Domain.User;

namespace WT.OpenIddict.Repository.Seed;

public class UserRoleSeedProvider : SeedProvider
{
    private readonly RoleManager<RoleDetails> _roleManager;
    private readonly UserManager<UserDetails> _userManager;

    public UserRoleSeedProvider(IServiceProvider serviceProvider) : base(serviceProvider)
    {
        _userManager = serviceProvider.GetRequiredService<UserManager<UserDetails>>();
        _roleManager = serviceProvider.GetRequiredService<RoleManager<RoleDetails>>();
    }

    public override async Task InitSeedData()
    {
        var adminUser = await _userManager.FindByNameAsync("admin");
        var adminRole = await _roleManager.FindByNameAsync("超级管理员");
        if (adminUser == null && adminRole == null)
        {
            var userDetails = new UserDetails();
            userDetails.UserName = "admin";
            userDetails.Email = "admin@openIddict.com";
            userDetails.PhoneNumber = "admin";
            userDetails.NormalizedUserName = "超级管理员";
            userDetails.TwoFactorEnabled = false;
            userDetails.RegisterTime = DateTime.Now;
            var userResult = await _userManager.CreateAsync(userDetails, "1q2w3E*");
            if (userResult.Succeeded)
            {
                var roleDetails = new RoleDetails();
                roleDetails.Name = "admin";
                roleDetails.NormalizedName = "超级管理员";
                var roleResult = await _roleManager.CreateAsync(roleDetails);
                if (roleResult.Succeeded) await _userManager.AddToRoleAsync(userDetails, roleDetails.Name);
            }
        }

        var mainUserRole = await _roleManager.FindByNameAsync("普通用户");
        if (mainUserRole == null)
        {
            var roleDetails = new RoleDetails();
            roleDetails.Name = "普通用户";
            roleDetails.NormalizedName = "普通用户";
            roleDetails.Description = "注册用户自带角色";
            var roleResult = await _roleManager.CreateAsync(roleDetails);
        }
    }
}